package org.mq.mymq.nameserver.handler;

import com.alibaba.fastjson2.JSON;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.mq.mymq.common.coder.TcpMsg;
import org.mq.mymq.common.enums.NameServerEventCode;
import org.mq.mymq.common.event.EventBus;
import org.mq.mymq.common.event.model.Event;
import org.mq.mymq.nameserver.event.model.NodeReplicationAckMsgEvent;

/**
 * @ClassName NodeReplicationServerHandler
 * @Description 注册中心节点向下游注册中心同步数据处理handler
 * @Author jiarong_ye
 * @Date 2025/6/24 16:33
 * @Version 1.0
 */
@ChannelHandler.Sharable
public class NodeSendMsgReplicationServerHandler extends SimpleChannelInboundHandler<TcpMsg> {
    private EventBus eventBus;

    public NodeSendMsgReplicationServerHandler(EventBus eventBus) {
        this.eventBus = eventBus;
        this.eventBus.init();
    }
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TcpMsg tcpMsg) throws Exception {
        int code = tcpMsg.getCode();
        byte[] body = tcpMsg.getBody();
        Event event = null;
        if (NameServerEventCode.NODE_REPLICATION_ACK_MSG.getCode() == code) {
            event = JSON.parseObject(body, NodeReplicationAckMsgEvent.class);
        }
        event.setChannelHandlerContext(channelHandlerContext);
        eventBus.publish(event);
    }
}
